package com.zito.common;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.downlove.common.RequestContext;
import com.zito.ErrMsgException;

/**
 * Title: 半月山庄工程核心模块 <br>
 * Description: com.downlove.database.page<br>
 * date: Mar 7, 2009 - 12:57:09 AM<br>
 * <br>
 * 
 * @author 蒋云海
 * @version 2.0
 */
public class Paginator {

	private int total = 0; // 总记录条数
	private int pageSize = 20; // 每页显示条数
	private int curPage = 1; // 当前所在页码
	private int totalpages = 0; // 总页数
	private int pagenumbegin = 0; // 当前页码显示的开始页码
	private int pagenumend = 0; // 在页面中显示的结束页码
	private int numperpage = 10; // 每页显示的页码数
	private int totalpagenumblock = 0; // 共有多少个页码块，如[pagenumbegin,2,3,4,5,...,
	// pagenumend]
	private int curpagenumblock = 0; // 当前处在第多少个页码块，如[pagenumbegin,12...,
	private HttpServletRequest request;
	private HttpServletResponse response;
	String url = "";

	/**
	 * 得到页面URL传来的参数与值，包括前面的问号,并且已经对URL进行UTF8编码。如："?page=3&key=val".
	 * 并且可以选择性的删除不需要的参数。 $Time: 2010-05-17$
	 * 
	 * @param request
	 * @param remove
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private String getQueryString(HttpServletRequest request, String[] remove) {
		String queryString = StringUtils.isBlank(request.getQueryString()) ? ""
				: request.getQueryString();
		Map map = request.getParameterMap();
		if (map.size() > 0) {
			Map newmap = new HashMap();
			newmap.putAll(map);
			if (remove != null) {
				for (String key : remove) {
					newmap.remove(key);
				}
			}
			StringBuilder temp = new StringBuilder("");
			int temI = 0;
			for (Object key : newmap.keySet()) {
				temp.append((temI == 0) ? "?" : "&");
				temp.append(key.toString()
						+ "="
						+ UnicodeToUTF8(((String[]) newmap.get(key))[0]));
				temI++;
			}
			return temp.toString();
		}
		return queryString;
	}

	private String UnicodeToUTF8(String strIn) {
		return strIn;
		//return conversionUnicode(strIn, "ISO8859_1", "utf-8");
	}

	/**
	 * 编码类型转换，一般用于中文字符的传递. 使用实例：
	 * 
	 * <pre>
	 * StringUtils.conversionUnicode(strIn, &quot;ISO8859_1&quot;, &quot;utf-8&quot;);
	 * </pre>
	 * 
	 * @param strIn
	 * @param sourceType
	 * @param converType
	 * @return String
	 */
	@SuppressWarnings("unused")
	private String conversionUnicode(String strIn, String sourceType,
			String converType) {
		String strOut = null;
		if (strIn == null || (strIn.trim()).equals("")) {
			return "";
		}
		try {
			byte[] b = strIn.getBytes(sourceType);
			strOut = new String(b, converType);
		} catch (Exception e) {
		}
		return strOut;
	}
	
    public static String getPageName(HttpServletRequest request) {
        String temp = request.getRequestURI();
        int point = temp.lastIndexOf("/");
        String tempName = temp.substring(point + 1, temp.length());
        return tempName;
    }

	public Paginator(RequestContext rc) throws NumberFormatException,
			ErrMsgException {
		getCPage(rc);
	}

	public Paginator(RequestContext rc, int total, int pagesize) {
		getCPage(rc);
		this.total = total;
		this.pageSize = pagesize;
		totalpages = (int) Math.ceil((double) total / pagesize);
	}

	public void init(int total, int pagesize) {
		this.total = total;
		this.pageSize = pagesize;
		totalpages = (int) Math.ceil((double) total / pagesize);
	}

	/**
	 * 返回数据集总数
	 * 
	 * @return
	 */
	public int Total() {
		return total;
	}

	/**
	 * 设置数据集总数
	 * 
	 * @param t
	 */
	// public void setTotal(int t) {
	// this.total = t;
	// }
	/**
	 * 返回每页显示数据数
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * 设置每页显示数据数
	 * 
	 * @param p
	 */
	// public void setPageSize(int p) {
	// this.pageSize = p;
	// }
	/**
	 * 返回总页数
	 */
	public int getTotalPages() {
		return totalpages;
	}

	/**
	 * 返回下一页的页码
	 * 
	 * @return
	 */
	public int getNextPage() {
		return (curPage <= totalpages) ? curPage + 1 : totalpages;
	}

	/**
	 * 返回上一页的页码
	 * 
	 * @return
	 */
	public int getPreviousPage() {
		return (curPage > 1) ? curPage - 1 : 1;
	}

	/**
	 * 返回当前所在页码
	 * 
	 * @return
	 */
	public int getCurrentPage() {
		return curPage;
	}

	// public int getCurPage() {
	// return curPage;
	// }
	private int getCPage(RequestContext rc) {
		this.request = rc.request();
		this.response = rc.response();
		try {
			curPage = RequestContext.get().param("page", 1);
		} catch (Exception e) {
			curPage = 1;
		}
		return curPage;
	}

	// 用当前页作为参数来初始化页码pagenumblock中用到的数据
	private void intpagenum() {
		if (totalpages == 0) {
			pagenumbegin = 0;
			pagenumend = 0;
			return;
		}

		// 总的页码块数
		totalpagenumblock = (int) totalpages / numperpage;
		if (totalpages % numperpage > 0) {
			totalpagenumblock += 1;
		}
		// if (TPages % numperpage > 0)
		// totalpagenumblock += 1;

		curpagenumblock = (int) (curPage / numperpage);
		if (curPage % numperpage > 0) {
			curpagenumblock += 1;
		}
		pagenumbegin = (curpagenumblock - 1) * numperpage + 1;
		if (pagenumbegin == 0) {
			pagenumbegin = 1;
		}
		if (totalpagenumblock == curpagenumblock) {
			pagenumend = totalpages; // 当最后一个页码块即为当前块时，使结束页码为总页码，
			// 避免当不足numperpage时会使得超出
		} else {
			pagenumend = pagenumbegin + numperpage - 1;
		}
	}

	/**
	 * 返回当前所处页码块
	 * 
	 * @param pagename
	 * @param query
	 * @return
	 */
	public String getCurPageBlock(String pagename, String query) {
		intpagenum();

		if (pagenumbegin == 0) {
			return "";
		}
		if (query == null) {
			this.url = pagename + "?";
		} else {
			this.url = pagename + "?" + query + "&";
		}
		return numPager();
	}

	public String getCurPageBlock() {
		intpagenum();

		if (pagenumbegin == 0) {
			return "";
		}
		makePageURI();
		return numPager();
	}

	public String makePageURI() {
		String[] remove = new String[] { "page" };
		String temp = getQueryString(this.request, remove);
		// System.out.println("getQueryString : "+temp);
		if ("".equals(temp)) {
			temp = "?";
		} else {
			temp = temp + "&";
		}
		this.url = getPageName(this.request) + temp;
//		System.out.println("url : "+ this.url);
//		System.out.println("encodeURL : "+ this.response.encodeURL(this.url));
		return this.url;
	}

	public String getUrl() {
		return this.url;
	}

	/**
	 * 返回当前所处页码块
	 * 
	 * @param pagename
	 * @return
	 */
	public String getCurPageBlock(String pagename) {
		return getCurPageBlock(pagename, null);
	}

	/**
	 * 返回当前所处页码块。属于CSS Block的
	 * 
	 * @param pagename
	 * @return
	 */
	public String getCssPageBlock(String pagename) {
		return getCssPageBlock(pagename, null);
	}

	/**
	 * 返回当前所处页码块。属于CSS Block的
	 * 
	 * @param pagename
	 * @param query
	 * @return
	 */
	public String getCssPageBlock(String pagename, String query) {
		intpagenum();

		if (pagenumbegin == 0) {
			return "";
		}

		if (query == null) {
			this.url = pagename + "?";
		} else {
			this.url = pagename + "?" + query + "&";
		}

		return numCssPager();
	}

	public String getCssPageBlock() {
		intpagenum();
		if (pagenumbegin == 0) {
			return "";
		}
		makePageURI();
		return numCssPager();
	}

	public String getCssPageBlockNew() {
		intpagenum();
		if (pagenumbegin == 0) {
			return "";
		}
		makePageURI();
		return numCssPagerNew();
	}

	/**
	 * 返回可用样式表定义显示的页码区域。属于CSS可定义样式 如：往前、往后、中间页码等
	 * 
	 * @return
	 */
	public String numCssPager() {
		StringBuffer outStr = new StringBuffer("");

		if (curpagenumblock > 1) { // 如果显示的是第二个页码段的页面
//			outStr.append("<a title=\"往前\" href=\"" + this.url + "page="
//					+ (pagenumbegin - 1) + "\">" + "&laquo; Previous" + "</a>");
			
			outStr.append("<a title=\"往前\" href=\"" + this.response.encodeURL(this.url + "page="
					+ (pagenumbegin - 1)) + "\">" + "&laquo; 前十页" + "</a>");
		}
		for (int i = pagenumbegin; i <= pagenumend; i++) {
			if (i == curPage) {
				outStr.append("<a href=\"" + this.response.encodeURL(this.url + "page=" + i) + "\" class=\"number current\">" + i + "</a>");
			} else {
//				outStr.append("<a href=\"" + this.url + "page=" + i + "\" class=\"number\">" + i
//						+ "</a>");
				outStr.append("<a href=\"" + this.response.encodeURL(this.url + "page=" + i) + "\" class=\"number\">" + i
						+ "</a>");
			}
		}
		if (curpagenumblock < totalpagenumblock) { // 如果显示的是第二个页码段的页面
//			outStr.append("<a title=\"往后\" href=\"" + this.url + "page="
//					+ (pagenumend + 1) + "\">" + "Next &raquo;" + "</a>");
			outStr.append("<a title=\"往后\" href=\"" + this.response.encodeURL(this.url + "page="
					+ (pagenumend + 1)) + "\">" + "后十页 &raquo;" + "</a>");
		}
		return outStr.toString();
	}
	
	public String numCssPagerNew() {
		StringBuffer outStr = new StringBuffer("");
		if (getCurrentPage() <= 1) { // 如果显示的是第一页
			outStr.append("<span class=\"current\">首页</span><span class=\"current\">上一页</span>");
		}

		if (getCurrentPage() > 1) { // 如果显示的是第二个页码段的页面
			outStr.append("<a title=\"首页\" href=\""
					+ this.response.encodeURL(this.url) + "\" class=\"texta\">"
					+ "首页" + "</a>");
			outStr.append("<a title=\"上一页\" href=\""
					+ this.response.encodeURL(this.url + "page="
							+ (getCurrentPage() - 1)) + "\" class=\"texta\">"
					+ "上一页" + "</a>");
		}
		for (int i = pagenumbegin; i <= pagenumend; i++) {
			if (i == curPage) {
				outStr.append("<a href=\""
						+ this.response.encodeURL(this.url + "page=" + i)
						+ "\" class=\"number current\">" + i + "</a>");
			} else {
				outStr.append("<a href=\""
						+ this.response.encodeURL(this.url + "page=" + i)
						+ "\" class=\"number\">" + i + "</a>");
			}
		}
		// <a href="#" class="texta">下一页</a><a href="#" class="texta">尾页</a>
		// getTotalPages getCurrentPage
		if (getCurrentPage() < getTotalPages()) { // 最后一页
			outStr.append("<a title=\"下一页\" href=\""
					+ this.response.encodeURL(this.url + "page="
							+ (getCurrentPage() + 1)) + "\" class=\"texta\">"
					+ "下一页" + "</a>");
			outStr.append("<a title=\"尾页\" href=\""
					+ this.response.encodeURL(this.url + "page=" + totalpages)
					+ "\" class=\"texta\">" + "尾页" + "</a>");
		} else {
			outStr.append("<span class=\"current\">下一页</span><span class=\"current\">尾页</span>");
		}
		return outStr.toString();
	}


	/**
	 * 返回可用样式表定义显示的页码区域。 如：往前、往后、中间页码等
	 * 
	 * @return
	 */
	public String numPager() {
		StringBuffer outStr = new StringBuffer("");

		if (curpagenumblock > 1) { // 如果显示的是第二个页码段的页面
			outStr.append("<a title=\"往前\" href=\"" + this.url + "page="
					+ (pagenumbegin - 1) + "\">" + "&laquo; Previous" + "</a> ");
		}
		for (int i = pagenumbegin; i <= pagenumend; i++) {
			if (i == curPage) {
				outStr.append(i + " ");
			} else {
				outStr.append("[<a href=\"" + this.url + "page=" + i + "\">"
						+ i + "</a>] ");
			}
		}
		if (curpagenumblock < totalpagenumblock) { // 如果显示的是第二个页码段的页面
			outStr.append("<a title=\"往后\" href=\"" + this.url + "page="
					+ (pagenumend + 1) + "\">" + "Next &raquo;" + "</a>");
		}
		return outStr.toString();
	}

	/**
	 * 跳转页，下拉框选择想去的页码，然后页面直接跳转
	 * 
	 * @return
	 */
	public String jumpPager() {
		StringBuffer outStr = new StringBuffer(numPager());

		outStr.append("<script language='javascript'>\n");
		outStr.append("<!--\n");
		outStr.append("function selpage_onchange()\n");
		outStr.append("{\n");
		outStr.append("location.href=\"" + url + "page=\"+selpage.value\n");
		outStr.append("}\n");
		outStr.append("//-->\n");
		outStr.append("</script>\n");
		outStr.append("&nbsp;&nbsp;到第&nbsp;<select name=selpage onchange='selpage_onchange()'>");
		for (int k = 1; k <= totalpages; k++) {
			outStr.append("<option value=" + k + ">" + k + "</option>");
		}
		outStr.append("</select>&nbsp;页");
		outStr.append("<script language='javascript'>\n");
		outStr.append("<!--\n");
		outStr.append("selpage.value=" + curPage + "\n");
		outStr.append("//-->\n");
		outStr.append("</script>\n");
		return outStr.toString();
	}
}
